package com.thundersoft.pickcolor.activity;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.thundersoft.pickcolor.R;
import com.thundersoft.pickcolor.bean.Color;
import com.thundersoft.pickcolor.utils.ColorUtils;
import com.thundersoft.pickcolor.utils.ShareUtils;
import com.thundersoft.pickcolor.utils.TextUtils;
import com.thundersoft.pickcolor.utils.ToastUtils;

/**
 * 转换工具
 */
public class ToolActivity extends AppCompatActivity {

    private EditText et_hex,et_rgb_r,et_rgb_g,et_rgb_b;
    private RadioGroup rg;
    private Button btn_change_color;
    private ImageView iv_tool_color;
    private TextView tv_tool_color_value;

    private Context mContext;
    private boolean isToRGB = true;
    private Color color;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tool);
        getSupportActionBar().setTitle(getResources().getString(R.string.tool_hex_rgb));

        // 显示返回键
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        initView();
        initData();
        rgListener();
        btnChangeColor();
        ivToolColorClick();
        tvToolColorValueClick();
    }

    // 初始化视图
    private void initView() {
        mContext = this;

        // EditText
        et_hex = findViewById(R.id.et_hex);
        et_rgb_r = findViewById(R.id.et_rgb_r);
        et_rgb_g = findViewById(R.id.et_rgb_g);
        et_rgb_b = findViewById(R.id.et_rgb_b);

        // RadioGroup&RadioButton
        rg = findViewById(R.id.rg);

        // Button
        btn_change_color = findViewById(R.id.btn_change_color);

        // ImageView&TextView
        iv_tool_color = findViewById(R.id.iv_tool_color);
        tv_tool_color_value = findViewById(R.id.tv_tool_color_value);
    }

    // 初始化数据
    private void initData() {
        String hex = et_hex.getText().toString().trim();
        String r = et_rgb_r.getText().toString().trim();
        String g = et_rgb_g.getText().toString().trim();
        String b = et_rgb_b.getText().toString().trim();
        tv_tool_color_value.setText(hex+"\n"+r+","+g+","+b);
        iv_tool_color.setBackgroundColor(android.graphics.Color.parseColor(hex));
        color = new Color(Integer.parseInt(r), Integer.parseInt(g), Integer.parseInt(b), hex, "搜索");
    }

    // 监听RadioGroup
    private void rgListener() {
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId == R.id.rb_to_rgb){
                    isToRGB = true;
                }else {
                    isToRGB = false;
                }
            }
        });
    }

    // 转换
    private void btnChangeColor() {
        btn_change_color.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isToRGB){
                    // hex转换成rgb
                    toRGB();
                }else {
                    // rgb转换成hex
                    toHex();
                }
            }
        });
    }

    private void toRGB() {
        String hex = et_hex.getText().toString().trim();
        if(hex.equals("")){
            ToastUtils.Info(mContext,getString(R.string.input_can_not_null));
        }else if(!CheckHex(hex)){
            ToastUtils.Info(mContext,getString(R.string.input_hex_error_re_input));
        } else {
            int[] rgb = ColorUtils.toRGB(hex);
            et_rgb_r.setText(String.valueOf(rgb[0]));
            et_rgb_g.setText(String.valueOf(rgb[1]));
            et_rgb_b.setText(String.valueOf(rgb[2]));

            tv_tool_color_value.setText(hex+"\n"+rgb[0]+","+rgb[1]+","+rgb[2]);
            iv_tool_color.setBackgroundColor(android.graphics.Color.parseColor(hex));

            color.setKind(getString(R.string.collect));
            color.setHexInt(hex);
            color.setrInt(rgb[0]);
            color.setgInt(rgb[1]);
            color.setbInt(rgb[2]);

        }
    }

    private boolean CheckHex(String hex) {
        String str = "0123456789abcdefgABCDEFG";

        // 一定要满足以'#'开头，一共7位
        if(hex.length()!=7 || hex.charAt(0)!='#'){
            return false;
        }else {
            // 2~7的取值范围
            for (int i = 1; i < hex.length(); i++) {
                boolean isContains = false;
                for (int j = 0; j < str.length(); j++) {
                    isContains = String.valueOf(hex.charAt(i)).equals(String.valueOf(str.charAt(j)));
                    if(isContains){
                        break;
                    }
                }
                if(!isContains){
                    return false;
                }
            }
            return true;
        }
    }

    private void toHex() {
        String r = et_rgb_r.getText().toString().trim();
        String g = et_rgb_g.getText().toString().trim();
        String b = et_rgb_b.getText().toString().trim();
        int rRGB = 0;
        int gRGB = 0;
        int bRGB = 0;
        if(!r.equals("")&&!g.equals("")&&!b.equals("")){
            rRGB = Integer.parseInt(r);
            gRGB = Integer.parseInt(g);
            bRGB = Integer.parseInt(b);
        }
        if(r.equals("")||g.equals("")||b.equals("")){
            ToastUtils.Info(mContext,getString(R.string.input_can_not_null));
        }else if(rRGB<0||rRGB>255||gRGB<0||gRGB>255||bRGB<0||bRGB>255){
            ToastUtils.Info(mContext,getString(R.string.input_rgb_error_re_input));
        }else{
            String hex = ColorUtils.toHex(rRGB,gRGB,bRGB);
            et_hex.setText(hex);

            tv_tool_color_value.setText(hex+"\n"+r+","+g+","+b);
            iv_tool_color.setBackgroundColor(android.graphics.Color.parseColor(hex));

            color.setKind(getString(R.string.collect));
            color.setHexInt(hex);
            color.setrInt(rRGB);
            color.setgInt(gRGB);
            color.setbInt(bRGB);
        }
    }



    private void ivToolColorClick() {
        // 点击事件
        iv_tool_color.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtils.Info(mContext,getString(R.string.long_click_collect_color));
            }
        });
        // 长按事件
        iv_tool_color.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if(queryData(color)){
                    insertData(color);
                    ToastUtils.Success(mContext,getString(R.string.collect_success));
                }else {
                    ToastUtils.Success(mContext,getString(R.string.has_been_collected));
                }
                return true;
            }
        });
    }

    // 添加数据
    private void insertData(Color color) {
        Uri uriColor = Uri.parse("content://com.thundersoft.pickcolor.provider/color");
        ContentValues values = new ContentValues();
        values.put("hexValue",color.getHexInt());
        values.put("rValue",color.getrInt());
        values.put("gValue",color.getgInt());
        values.put("bValue",color.getbInt());
        values.put("kind",mContext.getString(R.string.collect));
        values.put("userId",ShareUtils.getInt(mContext,"userId",0));
        mContext.getContentResolver().insert(uriColor,values);
    }

    // 查询数据
    private boolean queryData(Color color) {
        Uri uri = Uri.parse("content://com.thundersoft.pickcolor.provider/color");
        Cursor cursor = null;
        try {
            cursor = mContext.getContentResolver().query(uri,null,
                    "kind = ? and hexValue = ? and userId = ?",
                    new String[]{mContext.getString(R.string.collect), color.getHexInt(),
                            String.valueOf(ShareUtils.getInt(mContext, "userId",0))},null);
            if(cursor !=null){
                while (cursor.moveToNext()){
                    return false;// 已被收藏过了(当前用户)
                }
                return true;
            }else {
                return true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(cursor !=null){
                cursor.close();
            }
        }
        return false;
    }

    private void tvToolColorValueClick() {
        // 点击事件
        tv_tool_color_value.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtils.Info(mContext,getString(R.string.long_click_copy_color_values));
            }
        });
        // 长按事件
        tv_tool_color_value.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                // 复制
                String colorValue = tv_tool_color_value.getText().toString().trim();
                copyColorValue(colorValue);
                ToastUtils.Success(mContext,getString(R.string.copy_color_value_success));
                return true;
            }
        });

    }

    // 复制
    private void copyColorValue(String colorValue) {
        TextUtils.copy(mContext,colorValue);
    }

    // 菜单栏操作
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
